package demo;

import javafx.animation.PathTransition;
import javafx.animation.PathTransition.OrientationType;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;

// 路径动画
public class PathTransitionDemo extends Application {
	private Pane root = new Pane();
	private Polygon polygon = new Polygon();
	private ObservableList<Double> list;
	private Rectangle rectangle;
	private PathTransition pt;
	
	public static void main(String[] args) {
		launch(args);
	}
	
	@Override
	public void start(Stage stage) throws Exception {
		
		// 五角星
		polygon.setFill(null);
		polygon.setStroke(Color.GREEN);
		
	    list = polygon.getPoints();
	    list.addAll(150.0, 20.0);
	    list.addAll(75.0, 280.0);
	    list.addAll(280.0, 100.0);
	    list.addAll(20.0, 100.0);
	    list.addAll(225.0, 280.0);
	    
	    // 正方形
	    rectangle = new Rectangle(30, 30, Color.ORANGE);
	    rectangle.setArcWidth(15);
	    rectangle.setArcHeight(15);
	    root.getChildren().addAll(polygon, rectangle);
	    
	    Scene scene = new Scene(root, 300, 300);    
	    stage.setScene(scene);
		stage.show();
		
		// 动画
		pt = new PathTransition(Duration.seconds(10), polygon, rectangle);
		pt.setOrientation(OrientationType.ORTHOGONAL_TO_TANGENT);
		pt.setAutoReverse(true);
		pt.setCycleCount(Timeline.INDEFINITE);
		pt.play();
		
		// 监听
		root.widthProperty().addListener(e -> updatePath() );
		root.heightProperty().addListener(e -> updatePath() );
		
		// 事件
		root.setOnMouseClicked(e -> pt.playFromStart() );	// 重新开始
	}
	
	// 更新路径
	public void updatePath() {
		pt.stop();		// 先停止原来的动画
		list.clear();
		list.addAll(root.getWidth()/2, 20.0);
		list.addAll(root.getWidth()/4, root.getHeight()-20);
		list.addAll(root.getWidth()-20, root.getHeight()/3);
		list.addAll(20.0, root.getHeight()/3);
		list.addAll(root.getWidth()/4*3, root.getHeight()-20);
		pt.play();		// 开始新的动画
	}
}
